#!/usr/bin/python
"""
Normalizes whole day events of a icalendar file.
If DTSTART and DTEND arte datetime values and both have time 00:00 it converts them to date values without any time.

As first parameter a file name can be given for input. If none is given stdin is read.
The converted icalender file is written to stdout.
"""

from icalendar import Calendar, Event, vDatetime, vDate
import sys
import datetime

def parse_date(date_):
    return vDatetime.from_ical(str(date_))

def main(file_):
    cal = Calendar.from_string(file_.read())
    for component in cal.walk():
        if isinstance(component, Event):
            try:
                dtstart = parse_date(component['dtstart'])
                dtend = parse_date(component['dtend'])
            except ValueError:
                pass
            else:
                if dtstart.time() == datetime.time(0,0):
                    if dtend.time() == datetime.time(0,0):
                        sys.stderr.write("%s\t%s\n" % (component['dtstart'], component['dtend']))
                        dtstart = dtstart.date()
                        dtend = dtend.date()
                        component['dtstart'] = vDate(dtstart).ical()
                        component['dtend'] = vDate(dtend).ical()
                        sys.stderr.write("%s\t%s\n" % (component['dtstart'], component['dtend']))
                        
    sys.stdout.write(cal.as_string())
        
                    

if __name__ == "__main__":
    try:
        filename = sys.argv[1]
    except IndexError:
        main(sys.stdin)
    else:
        main(file(filename))
